"""
Authentication View for Desktop Application
桌面应用用户认证界面
"""

import logging
from typing import Optional, Dict, Any, Callable
import asyncio

import flet as ft
from flet import (
    Page,
    View,
    Container,
    Column,
    Row,
    Text,
    TextField,
    ElevatedButton,
    TextButton,
    Icon,
    Icons,
    Colors,
    Card,
    Divider,
    AlertDialog,
    Image,
    ProgressRing,
    Checkbox,
    Tabs,
    Tab,
)

from ..core.state_manager import StateManager
from ..services.api_client import APIClient

logger = logging.getLogger(__name__)


class AuthView:
    """认证视图类"""
    
    def __init__(self, page: Page, state_manager: StateManager, api_client: APIClient):
        self.page = page
        self.state_manager = state_manager
        self.api_client = api_client
        
        # UI组件引用
        self.login_username_field: Optional[TextField] = None
        self.login_password_field: Optional[TextField] = None
        self.login_remember_checkbox: Optional[Checkbox] = None
        self.login_button: Optional[ElevatedButton] = None
        self.login_progress: Optional[ProgressRing] = None
        
        self.register_username_field: Optional[TextField] = None
        self.register_email_field: Optional[TextField] = None
        self.register_password_field: Optional[TextField] = None
        self.register_confirm_password_field: Optional[TextField] = None
        self.register_button: Optional[ElevatedButton] = None
        self.register_progress: Optional[ProgressRing] = None
        
        # 创建标签页
        self.tabs = Tabs(
            tabs=[
                Tab(
                    text="登录",
                    icon=Icons.LOGIN,
                    content=self._create_login_form(),
                ),
                Tab(
                    text="注册",
                    icon=Icons.PERSON_ADD,
                    content=self._create_register_form(),
                ),
            ],
            on_change=self._on_tab_change,
        )
        
        # 创建主认证界面
        auth_content = Container(
            content=Row(
                controls=[
                    # 左侧：品牌信息
                    Container(
                        content=Column(
                            controls=[
                                Icon(
                                    Icons.BURST_MODE,
                                    size=80,
                                    color=Colors.PRIMARY,
                                ),
                                Text(
                                    "AI多模态内容生成平台",
                                    size=32,
                                    weight="bold",
                                    text_align="center",
                                ),
                                Text(
                                    "使用先进的AI技术，轻松创建图像、视频、音频等多媒体内容",
                                    size=16,
                                    color=Colors.ON_SECONDARY,
                                    text_align="center",
                                ),
                                Divider(height=40),
                                Row(
                                    controls=[
                                        Icon(Icons.STAR, color=Colors.AMBER, size=20),
                                        Text("支持多种AI模型", size=14),
                                    ], 
                                    spacing=5
                                ),
                                Row(
                                    controls=[
                                        Icon(Icons.STAR, color=Colors.AMBER, size=20),
                                        Text("简单易用的界面", size=14),
                                    ], 
                                    spacing=5
                                ),
                                Row(
                                    controls=[
                                        Icon(Icons.STAR, color=Colors.AMBER, size=20),
                                        Text("强大的内容管理", size=14),
                                    ], 
                                    spacing=5
                                ),
                                Row(
                                    controls=[
                                        Icon(Icons.STAR, color=Colors.AMBER, size=20),
                                        Text("实时预览和编辑", size=14),
                                    ], 
                                    spacing=5
                                ),
                            ],
                            spacing=20,
                            horizontal_alignment="center",
                            alignment="center",
                        ),
                        padding=40,
                        expand=True,
                    ),
                    # 右侧：认证表单
                    Container(
                        content=Column(
                            controls=[
                                Text(
                                    "开始使用",
                                    size=28,
                                    weight="bold",
                                    text_align="center",
                                ),
                                Text(
                                    "登录您的账户或创建新账户",
                                    size=14,
                                    color=Colors.ON_SECONDARY,
                                    text_align="center",
                                ),
                                Divider(height=30),
                                self.tabs,
                            ],
                            spacing=20,
                            horizontal_alignment="center",
                        ),
                        padding=40,
                        bgcolor=Colors.SURFACE,
                        border_radius=12,
                        width=400,
                    ),
                ],
                spacing=0,
                alignment="center",
                vertical_alignment="center",
            )
        )
        
        # 创建视图
        self.view = View(
            route="/auth",
            controls=[
                Container(
                    content=auth_content,
                    padding=20,
                    expand=True,
                    alignment=ft.alignment.center,
                ),
            ],
            padding=0,
            spacing=0,
        )
    
    def _create_login_form(self) -> Container:
        """创建登录表单"""
        # 用户名输入框
        self.login_username_field = TextField(
            label="用户名或邮箱",
            hint_text="请输入用户名或邮箱地址",
            prefix_icon=Icons.PERSON,
        )
        
        # 密码输入框
        self.login_password_field = TextField(
            label="密码",
            hint_text="请输入密码",
            password=True,
            prefix_icon=Icons.LOCK,
            can_reveal_password=True,
        )
        
        # 记住我复选框
        self.login_remember_checkbox = Checkbox(
            label="记住我",
            value=False,
        )
        
        # 登录按钮
        self.login_button = ElevatedButton(
            text="登录",
            icon=Icons.LOGIN,
            on_click=self._on_login_click,
            width=200,
        )
        
        # 登录进度指示器
        self.login_progress = ProgressRing(
            width=24,
            height=24,
            stroke_width=3,
            visible=False,
        )
        
        # 忘记密码链接
        forgot_password_button = TextButton(
            text="忘记密码？",
            on_click=self._on_forgot_password_click,
        )
        
        return Container(
            content=Column(
                controls=[
                    self.login_username_field,
                    self.login_password_field,
                    Row(
                        controls=[
                            self.login_remember_checkbox,
                            forgot_password_button,
                        ],
                        alignment="spaceBetween",
                    ),
                    Divider(height=20),
                    Row(
                        controls=[
                            self.login_progress,
                            self.login_button,
                        ],
                        alignment="center",
                        spacing=10,
                    ),
                ],
                spacing=15,
                horizontal_alignment="center",
            ),
        )
    
    def _create_register_form(self) -> Container:
        """创建注册表单"""
        # 用户名输入框
        self.register_username_field = TextField(
            label="用户名",
            hint_text="请输入用户名",
            prefix_icon=Icons.PERSON,
        )
        
        # 邮箱输入框
        self.register_email_field = TextField(
            label="邮箱",
            hint_text="请输入邮箱地址",
            prefix_icon=Icons.EMAIL,
        )
        
        # 密码输入框
        self.register_password_field = TextField(
            label="密码",
            hint_text="请输入密码",
            password=True,
            prefix_icon=Icons.LOCK,
            can_reveal_password=True,
        )
        
        # 确认密码输入框
        self.register_confirm_password_field = TextField(
            label="确认密码",
            hint_text="请再次输入密码",
            password=True,
            prefix_icon=Icons.LOCK,
            can_reveal_password=True,
        )
        
        # 注册按钮
        self.register_button = ElevatedButton(
            text="注册",
            icon=Icons.PERSON_ADD,
            on_click=self._on_register_click,
            width=200,
        )
        
        # 注册进度指示器
        self.register_progress = ProgressRing(
            width=24,
            height=24,
            stroke_width=3,
            visible=False,
        )
        
        return Container(
            content=Column(
                controls=[
                    self.register_username_field,
                    self.register_email_field,
                    self.register_password_field,
                    self.register_confirm_password_field,
                    Divider(height=20),
                    Row(
                        controls=[
                            self.register_progress,
                            self.register_button,
                        ],
                        alignment="center",
                        spacing=10,
                    ),
                ],
                spacing=15,
                horizontal_alignment="center",
            ),
        )
    
    # 事件处理函数
    async def _on_login_click(self, e) -> None:
        """处理登录按钮点击事件"""
        await self._perform_login()
    
    async def _perform_login(self) -> None:
        """执行登录操作"""
        if not self.login_username_field or not self.login_password_field:
            return
            
        username = self.login_username_field.value
        password = self.login_password_field.value
        
        # 验证输入
        if not username or not password:
            await self._show_error_dialog("请输入用户名和密码")
            return
            
        # 显示进度指示器
        self._set_login_progress(True)
        
        try:
            # 调用API进行登录
            result = await self.api_client.login(username, password)
            
            if result and result.get("access_token"):
                # 保存认证信息
                self.state_manager.set_auth_token(result["access_token"])
                self.state_manager.set_user_info(result.get("user", {}))
                
                # 导航到主界面
                await self.page.go_async("/main")
            else:
                await self._show_error_dialog("登录失败，请检查用户名和密码")
                
        except Exception as e:
            logger.error(f"Login failed: {e}")
            await self._show_error_dialog(f"登录失败: {str(e)}")
        finally:
            # 隐藏进度指示器
            self._set_login_progress(False)
    
    async def _on_register_click(self, e) -> None:
        """处理注册按钮点击事件"""
        await self._perform_register()
    
    async def _perform_register(self) -> None:
        """执行注册操作"""
        if not all([
            self.register_username_field,
            self.register_email_field,
            self.register_password_field,
            self.register_confirm_password_field
        ]):
            return
            
        username = self.register_username_field.value
        email = self.register_email_field.value
        password = self.register_password_field.value
        confirm_password = self.register_confirm_password_field.value
        
        # 验证输入
        if not all([username, email, password, confirm_password]):
            await self._show_error_dialog("请填写所有字段")
            return
            
        if password != confirm_password:
            await self._show_error_dialog("两次输入的密码不一致")
            return
            
        if len(password) < 6:
            await self._show_error_dialog("密码长度至少为6位")
            return
            
        # 显示进度指示器
        self._set_register_progress(True)
        
        try:
            # 调用API进行注册
            result = await self.api_client.register(username, email, password)
            
            if result and result.get("access_token"):
                # 保存认证信息
                self.state_manager.set_auth_token(result["access_token"])
                self.state_manager.set_user_info(result.get("user", {}))
                
                # 导航到主界面
                await self.page.go_async("/main")
                
                # 显示欢迎消息
                await self.page.show_snack_bar_async(
                    ft.SnackBar(
                        content=Text(f"欢迎，{username}！注册成功"),
                        action="好的",
                    )
                )
            else:
                await self._show_error_dialog("注册失败，请稍后重试")
                
        except Exception as e:
            logger.error(f"Registration failed: {e}")
            await self._show_error_dialog(f"注册失败: {str(e)}")
        finally:
            # 隐藏进度指示器
            self._set_register_progress(False)
    
    async def _on_forgot_password_click(self, e) -> None:
        """处理忘记密码点击事件"""
        await self._show_error_dialog("忘记密码功能暂未实现")
    
    def _on_tab_change(self, e) -> None:
        """处理标签页切换事件"""
        # 可以在这里添加标签页切换时的逻辑
        pass
    
    def _set_login_progress(self, show: bool) -> None:
        """设置登录进度指示器状态"""
        if self.login_progress and self.login_button:
            self.login_progress.visible = show
            self.login_button.disabled = show
            self.page.update()
    
    def _set_register_progress(self, show: bool) -> None:
        """设置注册进度指示器状态"""
        if self.register_progress and self.register_button:
            self.register_progress.visible = show
            self.register_button.disabled = show
            self.page.update()
    
    async def _show_error_dialog(self, message: str) -> None:
        """显示错误对话框"""
        dialog = AlertDialog(
            title=Text("错误"),
            content=Text(message),
            actions=[
                TextButton("确定", on_click=lambda e: self.page.close_dialog()),
            ],
        )
        self.page.dialog = dialog
        self.page.open_dialog()
        await self.page.update_async()
    
    def _validate_password(self, password: str) -> bool:
        """验证密码强度"""
        return len(password) >= 6
    
    def get_content(self) -> View:
        """获取视图内容"""
        return self.view